'''
Created on Nov 27, 2010

@author: behrooz
'''
from django.contrib.sites.models import Site
from amscms.core.utils import bitly
from amscms import tweepy, settings
from amscms.ams.models import AdProfile

def post_to_twitter(ad):
    domain = Site.objects.get_current().domain
    url = u'http://%s/ads/view/%s/' % (domain, ad.id)
    link = bitly.shorten_url(url)
    text = ad.title + " - " + ad.advertizer.__unicode__()
    mesg = u'%s - %s' % (text, link)
    if len(mesg) > 140:
        size = len(mesg + '...') - 140
        mesg = u'%s... - %s' % (text[:-size], link)
    
    auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
    auth.set_access_token(settings.TWITTER_ACCESS_TOKEN_KEY, settings.TWITTER_ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)
    api.update_status(mesg)
    
    AdProfile.objects.save_value(ad.id, "bitly_url", link)
    
    return
